<template>
  <view class="print-setup-page">
    <!-- 导航栏 -->
    <u-navbar 
      title="打印设置" 
      :border="true"
      left-icon="arrow-left"
      @leftClick="goBack"
    />
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="circle"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 打印设置内容 -->
    <view v-else class="setup-content">
      <!-- 文件信息 -->
      <view v-if="fileInfo" class="file-info-section">
        <view class="section-title">文件信息</view>
        <view class="file-card">
          <view class="file-header">
            <u-icon :name="getFileIcon(fileInfo.fileType)" size="24" color="#409eff"></u-icon>
            <view class="file-details">
              <text class="file-name">{{ fileInfo.originalName }}</text>
              <text class="file-meta">{{ formatFileSize(fileInfo.fileSize) }} · {{ fileInfo.pageCount || 1 }}页</text>
            </view>
          </view>
          <view v-if="fileInfo.previewUrl" class="file-preview">
            <image :src="fileInfo.previewUrl" mode="aspectFit" class="preview-image" />
          </view>
        </view>
      </view>
      
      <!-- 打印参数设置 -->
      <view class="print-options-section">
        <view class="section-title">打印参数</view>
        
        <!-- 纸张大小 -->
        <view class="option-group">
          <view class="option-label">纸张大小</view>
          <view class="option-items">
            <view 
              v-for="option in printConfigs.paper_size || []" 
              :key="option.value"
              class="option-item"
              :class="{ active: printOptions.paperSize === option.value }"
              @tap="selectOption('paperSize', option.value)"
            >
              <text class="option-text">{{ option.displayName }}</text>
              <text v-if="option.pointsMultiplier !== 1" class="option-multiplier">×{{ option.pointsMultiplier }}</text>
            </view>
          </view>
        </view>
        
        <!-- 颜色类型 -->
        <view class="option-group">
          <view class="option-label">颜色类型</view>
          <view class="option-items">
            <view 
              v-for="option in printConfigs.color_type || []" 
              :key="option.value"
              class="option-item"
              :class="{ active: printOptions.colorType === option.value }"
              @tap="selectOption('colorType', option.value)"
            >
              <text class="option-text">{{ option.displayName }}</text>
              <text v-if="option.pointsMultiplier !== 1" class="option-multiplier">×{{ option.pointsMultiplier }}</text>
            </view>
          </view>
        </view>
        
        <!-- 打印质量 -->
        <view class="option-group">
          <view class="option-label">打印质量</view>
          <view class="option-items">
            <view 
              v-for="option in printConfigs.print_quality || []" 
              :key="option.value"
              class="option-item"
              :class="{ active: printOptions.printQuality === option.value }"
              @tap="selectOption('printQuality', option.value)"
            >
              <text class="option-text">{{ option.displayName }}</text>
              <text v-if="option.pointsMultiplier !== 1" class="option-multiplier">×{{ option.pointsMultiplier }}</text>
            </view>
          </view>
        </view>
        
        <!-- 装订方式 -->
        <view v-if="printConfigs.binding_type && printConfigs.binding_type.length > 0" class="option-group">
          <view class="option-label">装订方式</view>
          <view class="option-items">
            <view 
              v-for="option in printConfigs.binding_type || []" 
              :key="option.value"
              class="option-item"
              :class="{ active: printOptions.bindingType === option.value }"
              @tap="selectOption('bindingType', option.value)"
            >
              <text class="option-text">{{ option.displayName }}</text>
              <text v-if="option.pointsMultiplier !== 1" class="option-multiplier">×{{ option.pointsMultiplier }}</text>
            </view>
          </view>
        </view>
        
        <!-- 打印份数 -->
        <view class="option-group">
          <view class="option-label">打印份数</view>
          <view class="quantity-selector">
            <u-icon 
              name="minus-circle" 
              size="32" 
              color="#409eff"
              :class="{ disabled: quantity <= 1 }"
              @tap="decreaseQuantity"
            />
            <view class="quantity-input">
              <input 
                v-model.number="quantity" 
                type="number" 
                min="1" 
                max="100"
                @blur="validateQuantity"
                class="quantity-value"
              />
            </view>
            <u-icon 
              name="plus-circle" 
              size="32" 
              color="#409eff"
              :class="{ disabled: quantity >= 100 }"
              @tap="increaseQuantity"
            />
          </view>
        </view>
        
        <!-- 高级选项 -->
        <view class="advanced-options">
          <view class="option-toggle" @tap="showAdvanced = !showAdvanced">
            <text class="toggle-text">高级选项</text>
            <u-icon :name="showAdvanced ? 'arrow-up' : 'arrow-down'" size="16" color="#909399"></u-icon>
          </view>
          
          <view v-if="showAdvanced" class="advanced-content">
            <!-- 双面打印 -->
            <view class="switch-option">
              <text class="switch-label">双面打印</text>
              <u-switch 
                v-model="printOptions.duplex" 
                active-color="#409eff"
                size="24"
              />
            </view>
            
            <!-- 页面范围 -->
            <view class="input-option">
              <text class="input-label">页面范围</text>
              <u-input 
                v-model="printOptions.pageRange" 
                placeholder="如：1-5,8,10-12"
                border="bottom"
                class="page-range-input"
              />
              <text class="input-hint">留空表示打印全部页面</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 费用预览 -->
      <view class="cost-preview-section">
        <view class="section-title">费用预览</view>
        <view class="cost-card">
          <view class="cost-item">
            <text class="cost-label">总页数</text>
            <text class="cost-value">{{ totalPages }}页</text>
          </view>
          <view class="cost-item">
            <text class="cost-label">打印份数</text>
            <text class="cost-value">{{ quantity }}份</text>
          </view>
          <view class="cost-item total">
            <text class="cost-label">需要积分</text>
            <text class="cost-value highlight">{{ estimatedCost }}积分</text>
          </view>
          <view class="cost-item">
            <text class="cost-label">当前积分</text>
            <text class="cost-value" :class="{ insufficient: userPoints < estimatedCost }">
              {{ userPoints }}积分
            </text>
          </view>
        </view>
      </view>
      
      <!-- 备注 -->
      <view class="notes-section">
        <view class="section-title">备注信息</view>
        <u-textarea 
          v-model="notes"
          placeholder="请输入特殊要求或备注信息（可选）"
          :maxlength="500"
          count
          height="120"
          border="surround"
        />
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <u-button 
          type="primary" 
          :disabled="!canCreateReservation || creating"
          :loading="creating"
          @click="createReservation"
          class="create-btn"
        >
          {{ creating ? '创建中...' : '创建预约' }}
        </u-button>
        
        <view class="button-tips">
          <u-icon name="info-circle" size="14" color="#909399"></u-icon>
          <text>预约有效期24小时，请及时到店打印</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'PrintSetup',
  data() {
    return {
      fileId: null,
      fileInfo: null,
      printConfigs: {},
      printOptions: {
        paperSize: '',
        colorType: '',
        printQuality: '',
        bindingType: '',
        duplex: false,
        pageRange: ''
      },
      quantity: 1,
      notes: '',
      showAdvanced: false,
      loading: false,
      creating: false,
      estimatedCost: 0
    }
  },
  
  computed: {
    ...mapState('user', ['userInfo']),
    
    // 用户积分
    userPoints() {
      return (this.userInfo && this.userInfo.points) || 0
    },
    
    // 总页数
    totalPages() {
      return ((this.fileInfo && this.fileInfo.pageCount) || 1) * this.quantity
    },
    
    // 是否可以创建预约
    canCreateReservation() {
      return this.printOptions.paperSize && 
             this.printOptions.colorType && 
             this.printOptions.printQuality &&
             this.userPoints >= this.estimatedCost &&
             this.quantity >= 1
    }
  },
  
  watch: {
    // 监听打印选项变化，重新计算费用
    printOptions: {
      handler() {
        this.calculateCost()
      },
      deep: true
    },
    
    // 监听份数变化
    quantity() {
      this.calculateCost()
    }
  },
  
  onLoad(options) {
    this.fileId = parseInt(options.fileId)
    if (this.fileId) {
      this.loadData()
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载数据
    async loadData() {
      this.loading = true
      
      try {
        await Promise.all([
          this.loadFileInfo(),
          this.loadPrintConfigs()
        ])
        
        // 设置默认选项
        this.setDefaultOptions()
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载文件信息
    async loadFileInfo() {
      const response = await this.$http.get(`/api/files/${this.fileId}`)
      if (response.data.success) {
        this.fileInfo = response.data.data
      }
    },
    
    // 加载打印配置
    async loadPrintConfigs() {
      const response = await this.$http.get('/api/print/configs')
      if (response.data.success) {
        this.printConfigs = response.data.data
      }
    },
    
    // 设置默认选项
    setDefaultOptions() {
      // 设置默认纸张大小
      const defaultPaperSize = this.printConfigs.paper_size && this.printConfigs.paper_size.find(option => option.isDefault)
      if (defaultPaperSize) {
        this.printOptions.paperSize = defaultPaperSize.value
      } else if (this.printConfigs.paper_size && this.printConfigs.paper_size.length > 0) {
        this.printOptions.paperSize = this.printConfigs.paper_size[0].value
      }
      
      // 设置默认颜色类型
      const defaultColorType = this.printConfigs.color_type && this.printConfigs.color_type.find(option => option.isDefault)
      if (defaultColorType) {
        this.printOptions.colorType = defaultColorType.value
      } else if (this.printConfigs.color_type && this.printConfigs.color_type.length > 0) {
        this.printOptions.colorType = this.printConfigs.color_type[0].value
      }
      
      // 设置默认打印质量
      const defaultPrintQuality = this.printConfigs.print_quality && this.printConfigs.print_quality.find(option => option.isDefault)
      if (defaultPrintQuality) {
        this.printOptions.printQuality = defaultPrintQuality.value
      } else if (this.printConfigs.print_quality && this.printConfigs.print_quality.length > 0) {
        this.printOptions.printQuality = this.printConfigs.print_quality[0].value
      }
    },
    
    // 选择选项
    selectOption(type, value) {
      this.printOptions[type] = value
    },
    
    // 增加份数
    increaseQuantity() {
      if (this.quantity < 100) {
        this.quantity++
      }
    },
    
    // 减少份数
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    // 验证份数
    validateQuantity() {
      if (this.quantity < 1) {
        this.quantity = 1
      } else if (this.quantity > 100) {
        this.quantity = 100
      }
    },
    
    // 计算费用
    async calculateCost() {
      if (!this.fileId || !this.printOptions.paperSize || !this.printOptions.colorType || !this.printOptions.printQuality) {
        return
      }
      
      try {
        const response = await this.$http.post('/api/print/calculate-cost', {
          fileId: this.fileId,
          printOptions: this.printOptions,
          quantity: this.quantity
        })
        
        if (response.data.success) {
          this.estimatedCost = response.data.data.pointsCost
        }
      } catch (error) {
        console.error('计算费用失败:', error)
      }
    },
    
    // 创建预约
    async createReservation() {
      if (!this.canCreateReservation || this.creating) return
      
      this.creating = true
      
      try {
        const response = await this.$http.post('/api/print/reservations', {
          fileId: this.fileId,
          printOptions: this.printOptions,
          quantity: this.quantity,
          notes: this.notes
        })
        
        if (response.data.success) {
          uni.showToast({
            title: '预约创建成功',
            icon: 'success'
          })
          
          // 跳转到预约详情页
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/print/reservation?id=${response.data.data.id}`
            })
          }, 1500)
        }
      } catch (error) {
        console.error('创建预约失败:', error)
        uni.showToast({
          title: (error.response && error.response.data && error.response.data.message) || '创建预约失败',
          icon: 'none'
        })
      } finally {
        this.creating = false
      }
    },
    
    // 获取文件图标
    getFileIcon(fileType) {
      if (!fileType) return 'file-text'
      
      if (fileType.includes('pdf')) return 'file-pdf'
      if (fileType.includes('word') || fileType.includes('document')) return 'file-word'
      if (fileType.includes('excel') || fileType.includes('sheet')) return 'file-excel'
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return 'file-ppt'
      if (fileType.includes('image')) return 'image'
      if (fileType.includes('text')) return 'file-text'
      
      return 'file'
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  }
}
</script>

<style lang="scss" scoped>
.print-setup-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-container {
  padding: 120rpx 40rpx;
  text-align: center;
  
  .loading-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #909399;
  }
}

.setup-content {
  padding-bottom: 40rpx;
}

.file-info-section, .print-options-section, .cost-preview-section, .notes-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30rpx;
}

.file-card {
  .file-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .file-details {
      margin-left: 16rpx;
      flex: 1;
      
      .file-name {
        display: block;
        font-size: 30rpx;
        color: #303133;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .file-meta {
        font-size: 26rpx;
        color: #909399;
      }
    }
  }
  
  .file-preview {
    .preview-image {
      width: 100%;
      height: 200rpx;
      border-radius: 12rpx;
    }
  }
}

.option-group {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .option-label {
    font-size: 30rpx;
    color: #303133;
    font-weight: 500;
    margin-bottom: 20rpx;
  }
  
  .option-items {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    
    .option-item {
      position: relative;
      padding: 20rpx 24rpx;
      background: #f8f9fa;
      border-radius: 12rpx;
      border: 2rpx solid transparent;
      min-width: 120rpx;
      text-align: center;
      
      &.active {
        background: #e7f4ff;
        border-color: #409eff;
        
        .option-text {
          color: #409eff;
          font-weight: 500;
        }
      }
      
      .option-text {
        font-size: 28rpx;
        color: #606266;
      }
      
      .option-multiplier {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        background: #f56c6c;
        color: white;
        font-size: 20rpx;
        padding: 4rpx 8rpx;
        border-radius: 8rpx;
        line-height: 1;
      }
    }
  }
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40rpx;
  
  .quantity-input {
    .quantity-value {
      width: 120rpx;
      height: 80rpx;
      text-align: center;
      font-size: 32rpx;
      border: 2rpx solid #dcdfe6;
      border-radius: 12rpx;
      background: white;
    }
  }
  
  .disabled {
    opacity: 0.4;
  }
}

.advanced-options {
  margin-top: 30rpx;
  
  .option-toggle {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    border-top: 1rpx solid #f0f0f0;
    
    .toggle-text {
      font-size: 30rpx;
      color: #606266;
    }
  }
  
  .advanced-content {
    padding-top: 20rpx;
    
    .switch-option {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 30rpx;
      
      .switch-label {
        font-size: 28rpx;
        color: #606266;
      }
    }
    
    .input-option {
      .input-label {
        display: block;
        font-size: 28rpx;
        color: #606266;
        margin-bottom: 16rpx;
      }
      
      .page-range-input {
        margin-bottom: 12rpx;
      }
      
      .input-hint {
        font-size: 24rpx;
        color: #909399;
      }
    }
  }
}

.cost-card {
  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.total {
      padding-top: 30rpx;
      border-top: 2rpx solid #f0f0f0;
      margin-top: 20rpx;
    }
    
    .cost-label {
      font-size: 30rpx;
      color: #606266;
    }
    
    .cost-value {
      font-size: 30rpx;
      color: #303133;
      font-weight: 500;
      
      &.highlight {
        color: #409eff;
        font-size: 34rpx;
        font-weight: 600;
      }
      
      &.insufficient {
        color: #f56c6c;
      }
    }
  }
}

.action-buttons {
  padding: 40rpx 20rpx;
  
  .create-btn {
    width: 100%;
    height: 88rpx;
    border-radius: 44rpx;
    margin-bottom: 20rpx;
  }
  
  .button-tips {
    display: flex;
    align-items: center;
    justify-content: center;
    
    text {
      margin-left: 8rpx;
      font-size: 24rpx;
      color: #909399;
    }
  }
}
</style>